package com.weishuang.monitor.leader.config.client;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishuang.monitor.leader.commons.entity.BaseEntity;
import com.weishuang.monitor.leader.commons.enums.SCODE;
import com.weishuang.monitor.leader.entity.ServersBaseInfo;
import com.weishuang.monitor.leader.service.IServersBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class ClientUserDetailsService implements UserDetailsService {

    @Autowired
    private IServersBaseInfoService serversBaseInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<ServersBaseInfo> eq = Wrappers.lambdaQuery(ServersBaseInfo.class).eq(BaseEntity::getStatus, SCODE.STATUS_NORMAL.getValue()).eq(ServersBaseInfo::getId, username);
        ServersBaseInfo one = serversBaseInfoService.getOne(eq);
        //客户端默认权限为ROLE_CLIENT
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_CLIENT"));
        ClientUserDetails clientUserDetails = new ClientUserDetails(one.getId(), one.getSecret(), grantedAuthorities);
        clientUserDetails.setSystemName(one.getSystemName());
        return clientUserDetails;
    }
}
